<?php
// +----------------------------------------------------------------------
// | XiaMiCMF - 代码如诗
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://shujuwajue.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小虾米 <509129@qq.com>
// +----------------------------------------------------------------------
namespace Admin\Model;

use Common\Model\CommonModel;

class MenuModel extends CommonModel
{
    protected $orderBy = array('sort' => 'ASC');

    protected $_validate = array(
        //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
        array('parent_id', 'require', '请选择上级菜单', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
        array('menu_name', 'require', '菜单名称不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
        array('app', 'require', '应用名称不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
        array('controller', 'require', '控制器名称不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
        array('action', 'require', '方法名称不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),

        array('app,controller,action', 'checkAction', '规则记录已经存在', self::MUST_VALIDATE, 'callback', self::MODEL_INSERT),
    );
    
    //验证规则是否重复添加
    public function checkAction($data) {
        //检查是否重复添加
        $find = $this->where($data)->find();
        if ($find) {
            return false;
        }
        return true;
    }

    /**
     * 得到某父级菜单所有子菜单，包括自己
     * @param number $parentid
     */
    public function get_menu_tree($parent_id = 0, $level = 1) {

        //只能三级
        if ($level > 3) return;

        $where = array();
        $where['parent_id'] = $parent_id;
        $where['status'] = 1;

        $menus = $this->where($where)->order(array("sort"=>"ASC"))->select();
        if (!$menus) {
            return false;
        }

        foreach ($menus as $key => $menu) {

            $rule = strtolower($menu['app'].'/'.$menu['controller'].'/'.$menu['action']);
            if (!x_check_rule(x_get_admin_id(),$rule)) {
                unset($menus[$key]);
                continue;//继续循环
            }

            $menus[$key]['url'] = U("{$menus[$key]['app']}/{$menus[$key]['controller']}/{$menus[$key]['action']}");
            $children = $this->get_menu_tree($menu['menu_id'], $level+1);
            if (!empty($children)) {
                $menus[$key]['children'] = $children;
            }
            unset($menus[$key]['app']);
            unset($menus[$key]['controller']);
            unset($menus[$key]['action']);
            unset($menus[$key]['status']);

        }

        return $menus;

    }

    /**
     * 获取所有的菜单
     * @param type $data
     * @return type
     */
    public function menusAll() {
        return $this->get_menu_tree(0);
    }
}

?>